import React, { useEffect, useState, Fragment } from "react";
import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import "./index.scss";
import useStatusBar from "../../uses/useStatusBar";
import { AtIcon } from "taro-ui";
import { NavProps } from "../../../types/components/nav";
import { IS_IOS } from "../../utils/system";

/**
 * Nav 导航栏组件
 */
const Nav = ({
  title,
  leftView,
  rightView,
  overlay = true,
  styles,
  onBack,
  leftStyle = { color: "#000" },
  middleStyle,
  renderCenter,
  rootPath,
  cbNavHeight
}: NavProps) => {
  const [statusHeight] = useStatusBar();
  const [pagesLen, setPagesLen] = useState(1);

  const barHeight = IS_IOS ? 44 : 48;

  useEffect(() => {
    setPagesLen(Taro.getCurrentPages().length);
  }, []);

  useEffect(() => {
    cbNavHeight && cbNavHeight(barHeight + statusHeight);
  }, []);

  const renderLet = () => {
    const content = leftView ? (
      leftView
    ) : (
      <AtIcon
        value={`${pagesLen > 1 ? "chevron-left" : "home"}`}
        size="20"
        color={leftStyle.color}
      ></AtIcon>
    );
    return (
      <View
        className="left-wrapper"
        style={leftStyle}
        onClick={() => {
          if (onBack) {
            return onBack();
          }
          if (pagesLen > 1) {
            Taro.navigateBack();
          } else {
            Taro.switchTab({
              url: rootPath ? rootPath : "/pages/index/index"
            });
          }
        }}
      >
        {content}
      </View>
    );
  };

  const renderRight = () => {
    const content = rightView ? rightView : null;
    return content;
  };

  return (
    <Fragment>
      <View
        className="navbar"
        style={`padding-top: ${statusHeight}px; height: ${barHeight}px; ${styles}`}
      >
        <View className="navbar-inner">
          {renderLet()}
          {renderCenter ? (
            renderCenter()
          ) : (
            <Text className="title" style={middleStyle}>
              {title}
            </Text>
          )}
          {renderRight()}
        </View>
      </View>
      {overlay ? (
        <View
          style={{
            height: barHeight + statusHeight
          }}
        ></View>
      ) : null}
    </Fragment>
  );
};

export default Nav;
